﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class KeyUnitEdit : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            TabContainer1.ActiveTab = TabContainer1.Tabs[0];
            // TabContainer1.Tabs[1].Visible = false;
            //////得到登陆者所属支队或大队id
            ////string DepartmentID = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
            //string DepartmentID = "300100";

            ////判断是大队还是支队,大队=显示派出所
            //string group = "";
            //if (group == "大队")
            //    ddlPoliceStations.Visible = true;
            //if (group == "支队")
            //    ddlPoliceStations.Visible = false;

            try
            {
                DBCls db = new DBCls();
                DataTable dt = new DataTable();
                ////读取本用户所在大队的派出所列表
                // dt = db.QueryDataTable("select DepartmentID,FullName from PoliceStationDepartments where ParentID='" + DepartmentID + "' ", "PoliceStation");
                //if (dt.Rows.Count > 0)
                //{
                //    ddlPoliceStations.Items.Clear();
                //    for (int i = 0; i < dt.Rows.Count; i++)
                //    {
                //        ddlPoliceStations.Items.Add(new ListItem(dt.Rows[i][1].ToString(), dt.Rows[i][0].ToString()));
                //    }
                //}
                lblDWGM_Police.Visible = false;
                ddlPoliceStations.Visible = false;
                //读取重点单位类型
                dt.Clear();
                dt = db.QueryDataTable("select KeyUnitTypeID,KeyUnitTypeDescript from KeyUnitType order by cast( keyunittypeid  as int)", "KeyUnitType");
                if (dt.Rows.Count > 0)
                {
                    ddlUnitType.Items.Clear();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        ddlUnitType.Items.Add(new ListItem(dt.Rows[i][1].ToString(), dt.Rows[i][0].ToString()));
                    }
                }

                //判断此支队大队是否已输入 重点单位总数
               
                    this.lblCount.Visible = true;
                    this.txtCount.Visible = true;
                    
                //重点单位类型对照表
                    string sql = "select KeyUnitTypeDescript,KeyUnitTypeName from KeyUnitType order by cast( keyunittypeid  as int) ";
                    SqlDataReader sqlReader = db.SqlReader(sql);

                    DataTable Dt = new DataTable();
                    DataRow dr;
                    Dt.Columns.Add("KeyUnitTypeDescript", typeof(string));    //第几类
                    Dt.Columns.Add("KeyUnitTypeName", typeof(string));   //类型全称



                    while (sqlReader.Read())
                    {
                        dr = Dt.NewRow();
                        dr[0] = sqlReader[0].ToString();
                        dr[1] = sqlReader[1].ToString();

                        Dt.Rows.Add(dr);
                    }
                    sqlReader.Close();
                    this.DataList1.DataSource = new DataView(Dt);
                    this.DataList1.DataBind();
            }
            catch
            {
                Response.Write("<script language=javascript>alert('页面绑定信息出错，请刷新。')</script>");
            }


            string id = string.Empty;
            try
            {
                //编辑功能
                //获得重点单位id
                id = Request.Params["id"];
                //根据id赋值页面
                try
                {
                    ViewState.Add("PerformanceID",id);

                    DBCls db = new DBCls();

                    string sql = "select * from Performance where PerformanceID='" + id + "'";
                    DataTable dt = db.QueryDataTable(sql, "pers");
                    if (dt.Rows.Count > 0)
                    {
                        //单位总数
                        string DepartmentID = dt.Rows[0][8].ToString();
                        DataTable t2 = db.QueryDataTable("select Counts from KeyUnitCount where DepartmentID='" + DepartmentID + "'","dsss");
                        if(t2.Rows.Count>0)
                            txtCount.Text = t2.Rows[0][0].ToString();

                        //单位名称
                        txtUnitName.Text = dt.Rows[0][3].ToString();

                        //是否完成
                        string s=dt.Rows[0][5].ToString();
                        if (RadioButtonList1.Items[0].Value == s)
                            RadioButtonList1.Items[0].Selected = true;
                        else
                            RadioButtonList1.Items[1].Selected = true;
                        //单位类型
                        string type = dt.Rows[0][9].ToString();
                        for (int i = 0; i < ddlPoliceStations.Items.Count; i++)
                        {
                            if (ddlPoliceStations.Items[i].Value == type)
                            {
                                ddlPoliceStations.Items[i].Selected = true;
                                break;
                            }
                        }
                        //单位信息
                        txtUnitInfo.Text = dt.Rows[0][4].ToString();
                        //完成情况
                        txtPerformanceInfo.Text = dt.Rows[0][6].ToString();
                        //图片列表
                        BindDateList(id);
                    }
                   
                }
                catch
                {
                    //查询错误
                    Response.Write("<script language=javascript>alert('获取单位信息错误！"+id+"')</script>");
                    return;
                }
            }
            catch
            {
                Response.Write("<script language=javascript>alert('获取单位信息错误！')</script>");
            }
        }
    }
    //保存重点单位
    protected void btnSave_Click(object sender, EventArgs e)
    {
        ////得到登陆者所属支队或大队id
        //string DepartmentID = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        ////得到登陆者名称
        //string username = User.Identity.Name;

        //重点单位id
        string PerformanceID = ViewState["PerformanceID"].ToString();

        string counts = txtCount.Text;//单位总数

        //派出所
        string police = string.Empty;
        if (ddlPoliceStations.Visible)
            police = ddlPoliceStations.SelectedValue.ToString();
        else
            police = "";

        string unitName = txtUnitName.Text;      //单位名称
        string state = RadioButtonList1.SelectedValue.ToString();   //是否完成
        string unitType = ddlUnitType.SelectedValue.ToString();     //单位类型
        string unitInfo = txtUnitInfo.Text;     //单位简介
        string info = txtPerformanceInfo.Text;  //完成情况

        DateTime dtime = DateTime.Now;



        try
        {
            if (CheckUnitNameIsSame(unitName))
            {
                Response.Write("<script language=javascript>alert('保存失败，此单位名称已存在！')</script>");
                return;
            }

            DBCls db = new DBCls();

            //修改应完成总数
            string did = "select DepartmentID from Performance where PerformanceID='" + PerformanceID + "'";
            DataTable zd = db.QueryDataTable(did, "did");
           
            
            string sql1 = "update KeyUnitCount set Counts='" + counts + "' where DepartmentID='" + zd.Rows[0][0].ToString() + "'";
            
            //修改重点单位
            string sql2 = "update Performance set KeyUnitName='" + unitName + "',KeyUnitInfo='" + unitInfo + "',PerformanceState='" + state + "',PerformanceInfo='" + info + "',WriteTime='" + dtime + "',KeyUnitTypeID='" + unitType + "' where PerformanceID='" + PerformanceID + "'";

            bool rsl = false;

            if (txtCount.Visible)
                rsl = db.ExcuteSql2(sql1, sql2);
            else
                rsl = db.ExcuteSql1(sql2);

            if (rsl)
            {
                Response.Write("<script language=javascript>alert('修改成功！')</script>");
                
                //TabContainer1.Tabs[1].Visible = true;
                //TabContainer1.ActiveTab = TabContainer1.Tabs[1];
                return;
            }
            else
            {
                Response.Write("<script language=javascript>alert('修改失败！请重新检查填写信息。')</script>");
                return;
            }
        }
        catch
        {
            Response.Write("<script language=javascript>alert('修改失败！请重新检查填写信息。')</script>");
            return;
        }
    }
    /// <summary>
    /// 绑定显示图片和说明
    /// </summary>
    /// <param name="PerformanceID">单位id</param>
    void BindDateList(string PerformanceID)
    {
        DBCls db = new DBCls();
        string sql = "select PerformancePicID,PictureUrl,PictureDescript,PictureType from PerformancePic where PerformanceID='" + PerformanceID + "' order by case PictureType when '单位概貌' then 1 when '检查和整改火灾隐患' then 2 when '扑救初期火灾' then 3 when '组织引导人员疏散逃生' then 4 when '消防安全知识宣传教育培训' then 5 end ";
        SqlDataReader sqlReader = db.SqlReader(sql);

        DataTable Dt = new DataTable();
        DataRow dr;
        Dt.Columns.Add("PerformancePicID", typeof(string));    //主键
        Dt.Columns.Add("PictureUrl", typeof(string));   //图片地址
        Dt.Columns.Add("PictureDescript", typeof(string));   //图片描述
        Dt.Columns.Add("PictureType", typeof(string));    //图片类型

        int gm = 0;
        int jc = 0;
        int pj = 0;
        int zz = 0;
        int xf = 0;

        while (sqlReader.Read())
        {
            dr = Dt.NewRow();

            string type = sqlReader[3].ToString();
            
            dr[0] = sqlReader[0].ToString();
            dr[1] = sqlReader[1].ToString();
            dr[2] = sqlReader[2].ToString();
            dr[3] = type;
            Dt.Rows.Add(dr);

            if (type.Contains("概貌"))
            {
                gm += 1;
                if (gm > 3)
                    rblImgType.Items[1].Enabled = true;
            }
            else if (type.Contains("检查"))
            {
                jc += 1;
                if (jc > 3)
                    rblImgType.Items[2].Enabled = true;
            }
            else if (type.Contains("扑救"))
            {
                pj += 1;
                if (pj > 3)
                    rblImgType.Items[3].Enabled = true;
            }
            else if (type.Contains("组织"))
            {
                zz += 1;
                if (zz > 3)
                    rblImgType.Items[4].Enabled = true;
            }
            else if (type.Contains("消防"))
            {
                xf += 1;
            }

        }
        string s = "已上传图片数：";
        lblGM.Text = s + gm;
        lblJC.Text = s + jc;
        lblPJ.Text = s + pj;
        lblZZ.Text = s + zz;
        lblXF.Text = s + xf;

        sqlReader.Close();
        this.DltList.DataSource = new DataView(Dt);
        this.DltList.DataBind();
    }
    protected void btnImgDel_Command(object sender, CommandEventArgs e)
    {
        if (e.CommandArgument == null)
            return;
        string id = e.CommandArgument.ToString();
        DBCls db = new DBCls();
        try
        {
            //重点单位id
            string performanceid = ViewState["PerformanceID"].ToString();

            string sqls = "select picturetype from performancepic where performanceid='" + performanceid + "' and  picturetype = ( select picturetype from performancepic where performancepicid='" + id + "')";
            DataTable dt = db.QueryDataTable(sqls, "pics");
            if (dt.Rows.Count < 5)
            {
                Response.Write("<script language=javascript>alert('图片类型 " + dt.Rows[0][0].ToString() + " 的图片不得少于4张，删除前请先上传足够的图片。')</script>");
                return;
            }

            if (db.ExcuteSql1_Tran("delete PerformancePic where PerformancePicID='" + id + "'"))
            {
                Response.Write("<script language=javascript>alert('删除成功。')</script>");
                BindDateList(performanceid);
            }
        }
        catch
        {
            Response.Write("<script language=javascript>alert('删除失败。')</script>");
        }
    }
    protected void btnUpLoad_Click(object sender, EventArgs e)
    {
        string PerformanceID = string.Empty;
        try
        {
            //读取单位id
            PerformanceID = ViewState["PerformanceID"].ToString();
        }
        catch
        {
            //TabContainer1.ActiveTab = TabContainer1.Tabs[0];
            Response.Write("<script language=javascript>alert('请先保存重点单位信息。')</script>");
            return;
        }
        //保存图片
        string path = string.Empty;
        bool img = SaveImg("", out path);
        if (img)
        {
            try
            {
                DBCls db = new DBCls();
                string id = System.Guid.NewGuid().ToString();
                string sql = "insert into PerformancePic values ('" + id + "','" + PerformanceID + "','" + path + "','" + txtDescript.Text + "','" + rblImgType.SelectedValue.ToString() + "')";
                if (db.ExcuteSql1_Tran(sql))
                {
                    Response.Write("<script language=javascript>alert('图片保存成功。')</script>");
                    //重新绑定并显示图片和说明
                    BindDateList(PerformanceID);
                }
            }
            catch (Exception ex)
            {

                {
                    //删除图片
                }
                Response.Write("<script language=javascript>alert('图片保存失败！请重新上传。')</script>");
            }
        }
        else
        {
            Response.Write("<script language=javascript>alert('图片格式不正确，请上传 *.bmp,*.jpg,*.jpeg 格式图片')</script>");
        }
    }
    /// <summary>
    /// 上传图片
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    private bool SaveImg(string name1, out string localPath)
    {
        HttpFileCollection files = HttpContext.Current.Request.Files;
        System.Text.StringBuilder strMsg = new System.Text.StringBuilder();

        bool fileOK = false;
        HttpPostedFile postedFile = files[0];

        string fileName, fileExtension;
        fileName = System.IO.Path.GetFileName(postedFile.FileName);
        if (fileName != "")
        {
            fileExtension = System.IO.Path.GetExtension(fileName);
            String[] allowedExtensions = { ".bmp", ".jpg", ".jpeg" };
            for (int i = 0; i < allowedExtensions.Length; i++)
            {
                if (fileExtension.ToLower() == allowedExtensions[i])
                {
                    fileOK = true;
                    break;
                }
            }
        }
        if (fileOK)
        {

            //Bitmap bm = new Bitmap(path);
            //本地image文件夹路径
            string sPath = System.Web.HttpContext.Current.Request.MapPath("UpLoadImages/");
            //文件扩展名
            fileExtension = System.IO.Path.GetExtension(fileName).ToLower();
            //随机文件名
            Random rnd = new Random();
            string newName = DateTime.Now.ToString().Replace("-", "").Replace(":", "").Replace(" ", "") + rnd.Next(1000).ToString();
            localPath = "UpLoadImages/" + newName + fileExtension;
            postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("UpLoadImages/") + newName + fileExtension);

            return true;

        }
        else
        {
            //提示
            localPath = "";
            return false;
        }

    }
    /// <summary>
    /// 查询是否存在同名重点单位。存在=true；不存在=false
    /// </summary>
    /// <param name="unitname"></param>
    /// <returns></returns>
    private bool CheckUnitNameIsSame(string unitname)
    {
        DBCls db=new DBCls();
        string sql = "select performanceid from performance where keyunitname = '"+unitname+"'";
        DataTable dt = db.QueryDataTable(sql, "issame");
        if (dt.Rows.Count > 0)
            return true;
        else
            return false;
    }
}
